<template>
    <div class="sidebar">
        <Card dis-hover class="bg-grey" style="font-size:14px;">
            <p slot="title" class="ellipsis" :title="roomName">
                房间：{{ roomName }}
            </p>
            <Button type="primary" size="small" @click="openRoom" slot="extra" style="position:relative;top:-2px;">详情</Button>
            <Button type="primary" size="small" slot="extra" class="close-btn" @click="close" style="position:relative;top:-2px;">收起</Button>

            <template v-if="isShowRenterDetail">

                <Row style="margin-top:-5px;">
                    <Col span="24" class="info-right">
                    <strong>租客：</strong>
                        {{ tenantName ? tenantName : '无'}}
                        <Button type="ghost" class="float-right"  size='small' v-if="!room.lease" @click="setCheckInVisible(true)" v-pmis="30">入住</Button>
                        <Button type="ghost" size='small' class="float-right" v-if="room.lease" @click="throwLease" v-pmis="30">退租</Button>
                    </Col>
                </Row>
                <Row>
                    <Col span="24" class="info-right">
                        <strong>手机：</strong>
                    {{tenantPhone ? tenantPhone : '无'}}
                    </Col>
                </Row>
                <Row class="line">
                    <Col span="24" class="info-right">
                        <strong>租约有效期：</strong>
                        <template v-if="room.lease">
                            {{room.lease.lease_range[0] | formatDate}} 至
                            {{room.lease.lease_range[1] | formatDate}}
                        </template>
                        <template v-else>
                            无
                        </template>
                    </Col>
                </Row>

                <!-- 房间信息暂无密码有效期 -->
                <!-- <Row class="line" v-if="locks.length">
                    <Col span="12" class="info-right">租客密码有效期：</Col>
                    <Col span="12">-</Col>
                </Row> -->
            </template>

            <template v-else>
                <Row class="line special-line">
                    {{renterTip}}
                </Row>
            </template>

            <Row class="line" v-for="item in locks" :key="item.id">
                <Col span="24" class="info-right">
                    <strong>门锁状态：</strong>
                    <span v-for="(status, index) in lockStatus(item)" :key="status.label" :class="status.class">
                        <span v-show="index > 0"> / </span>
                        {{status.label}}
                    </span>
                    <Button class="float-right" style="margin-right:-5px;width:80px;line-height:15px" type="ghost" @click="showLicenseRecord">授权管理</Button>
                </Col>
            </Row>

            <Row class="line" v-for="item in accesss" :key="item.id">
                <Col span="24" class="info-right">
                    <strong>门禁状态：</strong>
                    <span :class="{ green: item.online === 1, red: item.online === 2}">
                        {{ item.online === 1 ? '在线' : '离线' }}
                    </span>
                </Col>
            </Row>

            <template v-if="elemeters && elemeters.length">
                <Row>
                    <Col span="24" class="info-right"><strong>付费模式：</strong>{{ payMode }}</Col>
                </Row>
                <Row v-if="payMode == '预付费'">
                    <Col span="24" class="info-right"><strong>剩余电量：</strong>{{ leftPower }}度</Col>
                </Row>
            </template>

            <Row v-for="(item, idx) in elemeters" :key="item.id" class="line">
                <Col span="24" class="info-right"><strong>电表{{ idx + 1 }}：</strong>

                    <span :class="{ green: item.online == 1, red: item.online != 1 }">{{ item.online == 1 ? '在线' : '离线' }}</span>
                    <template v-if="item.data">
                    / <span :class="{ green: item.switch == 1, red: item.switch != 1 }">{{ item.switch == 1 ? '通电' : '断电' }}</span>
                    </template>
                </Col>
            </Row>

            <Row type="flex" justify="space-around" style="padding:20px 4px 30px 4px;">
                <Button class="add-device-btn" type="primary" @click='handleCreateAppointment' v-pmis="24">新建工单</Button>

            </Row>
        </Card>

        <!-- 入住 -->
        <renterCheckIn
            :home="home"
            :room="room"
            v-if="isCheckInModalVisible"
            @cancelCheckIn="setCheckInVisible(false)"
            @checkInSuccess="checkInSuccess"/>

        <!-- 退租 -->
        <renterOut
            :room="room"
            v-if="isRenterThrowLeaseVisible"
            @cancelOut="cancelThrowLease"
            @outSuccess="throwLeaseSuccess"/>


        <Modal :width="700" v-model="modal.appointmentVisible" footer-hide :mask-closable="false">
            <ticketCreate
                v-if="modal.appointmentVisible"
                @on-close="modal.appointmentVisible = false"
                fixedHome
                :ticket.sync="modal.ticket"
                :home="{home_type: home && home.home_type}"
                ></ticketCreate>
        </Modal>

        <!-- 授权管理 -->
        <licenseRecord v-if="isLicenseRecordVisible" :visible="true" :room="room" :home="home" :roomName="roomName" @on-close="closeLicenseRecord"/>
    </div>
</template>

<script>
import dayjs from 'dayjs'
import { RoomTypeEnum, DeviceTypeEnum, ElemeterPayMode } from '@/libs/const'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import renterCheckIn from '../renter/renterCheckIn.vue'
import renterOut from '../renter/renterOut.vue'
import licenseRecord from './licenseRecord.vue'
import ticketCreate from '../ticket/create-components/ticket-create'

export default {
  name: 'sidebar',
  components: {
    renterCheckIn,
    renterOut,
    licenseRecord,
    ticketCreate
  },
  props: {
    home: Object,
    room: Object
  },

  data () {
    return {
      RoomTypeEnum: RoomTypeEnum,
      DeviceTypeEnum: DeviceTypeEnum,
      isLicenseRecordVisible: false,
      isCheckInModalVisible: false,
      isRenterThrowLeaseVisible: false,
      ticket: {
        type: 1, // 快捷操作房间
        location: '',
        id: '', // 房源ID
        room_id: '', // 房间id
        room_number: '' // 房间名
      },
      modal: {
        appointmentVisible: false,
        serviceVisible: false,
        ticket: null,
        data: null
      },
      accessControls: []
    }
  },

  filters: {
    formatDate (date) {
      return dayjs(date).format('YYYY-MM-DD')
    }
  },
  watch: {
    room: {
      deep: true,
      handler (room) {
        this.accessControls = []
        if (room && room.room_type === RoomTypeEnum.PUBLIC) {
          this.initAccessControl()
        }
      }
    }
  },

  computed: {
    /**
        * 是否显示租客详情
        */
    isShowRenterDetail () {
      if (this.home && this.room) {
        const { lease_type } = this.home
        const { room_type } = this.room

        // console.log('lease_type', lease_type, 'room_type', room_type);
        if (room_type === this.RoomTypeEnum.PUBLIC) { // 当房间为公区的时候
          return lease_type === 2
        } else { // 当房间为普通房间的时候
          return lease_type !== 2
        }
      } else {
        return false
      }
    },

    renterTip () {
      return (this.room && this.room.room_type === this.RoomTypeEnum.PUBLIC)
        ? '分租房源，公区不支持预付费及租客入住'
        : '整租房源，房间不支持办理租客入住，请在公区登记入住或增加同租人'
    },

    roomName () {
      let room = this.room
      if (room) {
        if (room.room_type === RoomTypeEnum.PUBLIC) {
          let parent_ids = room.parent_ids
          if (!parent_ids || !parent_ids.length) {
            return '公区'
          }
          if (parent_ids && parent_ids.length === 1) {
            return room.room_name + '公区'
          }
        }
        return room.room_name
      }
      return ''
    },
    tenantName () {
      let room = this.room
      let name = room && room.lease && room.lease.tenant ? room.lease.tenant.name : ''
      return name
    },
    tenantPhone () {
      let room = this.room
      let phone = room && room.lease && room.lease.tenant ? room.lease.tenant.phone : ''
      return phone
    },
    payMode () {
      if (this.room) {
        const payType = this.room.pay_type
        if (!payType) {
          return '未知'
        } else {
          return ElemeterPayMode.properties[payType].text
        }
      }
      return '无'
    },

    leftPower () {
      let room = this.room
      if (room) {
        return util.getLeftElectric(room)
      }
      return '0.0000'
    },

    locks () {
      let room = this.room
      if (!room || !room.devices) {
        return []
      }

      let locks = []
      room.devices.forEach(item => {
        if (item.device_type === DeviceTypeEnum.LOCK) {
          locks.push(item)
        }
      })

      return locks
    },

    elemeters () {
      let room = this.room
      if (!room || !room.devices) {
        return []
      }

      let elemeters = []
      room.devices.forEach(item => {
        if (item.device_type === DeviceTypeEnum.ELEMETER) {
          elemeters.push(item)
        }
      })

      return elemeters
    },
    accesss () {
      const { room } = this
      if (!room) return []
      const m3 = room.devices.filter(device => device.device_type === DeviceTypeEnum.ACCESS_CONTROL)
      return [ ...m3, ...this.accessControls ]
    }
  },
  methods: {
    /**
         * !!!!! 这里要兼容m2 m3两种门禁
         */
    async initAccessControl () {
      const { id } = this.home
      const accessControls = await http.req(api.face_access_of_home, [ id ], null, true)
      if (accessControls) this.accessControls = accessControls
    },
    lockStatus (lock) {
      if (!lock) return []
      const result = []
      const isOnline = {}
      // const isLocking = {};
      const { online, low_power, longtime_no_open } = lock
      // const hasLongtimeNocloseLock = [ 'lk-25', 'lk-17', 'lk-18', 'T3S', 'T2S', 'D2S' ].some(modelType => [ type, model ].includes(modelType.toLowerCase()) || [ type, model ].includes(modelType.toUpperCase()));
      isOnline.label = online === 1 ? '在线' : '离线'
      isOnline.class = online === 1 ? 'green' : 'red'
      result.push(isOnline)
      if (low_power) {
        result.push({ label: '低电', class: 'red' })
      }
      if (longtime_no_open) {
        result.push({ label: '长时间未开门', class: 'red' })
      }
      // if (hasLongtimeNocloseLock) {
      //     isLocking.label = !longtime_no_close ? '已锁' : '未锁'; // 暂时未有虚掩状态
      //     isLocking.class = !longtime_no_close ? 'green' : 'red';
      //     return [ isOnline, isLocking ];
      // }
      return result
    },
    handleCreateService () {
      this.modal.data = {
        home: this.home,
        room_id: this.room.id
      }
      this.modal.serviceVisible = true
    },
    handleCreateAppointment () {
      const { id, address, block, city, district, home_name, province, number } = this.home
      // 使用工单返回数据结构
      this.modal.ticket = {
        home_id: id,
        subscribe: {},
        ticket_product_statistics: [],
        ticket_devices: [
          {
            room_id: this.room.id,
            room_name: this.room.room_name
          }
        ],
        home_info: {
          address,
          block,
          city,
          district,
          home_name,
          province,
          number
        }
      }
      this.modal.appointmentVisible = true
    },

    setCheckInVisible (v) {
      this.isCheckInModalVisible = v
    },

    checkInSuccess () {
      this.isCheckInModalVisible = false
      this.$emit('on-update')
    },

    cancelThrowLease () {
      this.isRenterThrowLeaseVisible = false
    },

    throwLeaseSuccess () {
      this.isRenterThrowLeaseVisible = false
      this.$emit('on-update')
    },

    throwLease () {
      util.log('throwLease----')
      this.isRenterThrowLeaseVisible = true
    },

    closeLicenseRecord () {
      this.isLicenseRecordVisible = false
    },

    showLicenseRecord () {
      this.isLicenseRecordVisible = true
    },

    close () {
      this.$emit('on-close')
    },

    delDevice () {
      http.request(this, api.lock_del, [16, 17], null, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('删除成功')
      })
    },

    openRoom () {
      // const homeId=this.room.home_id
      // const roomId=this.room.id
      // this.$router.push({
      //     path: `/tenancy-device/${homeId}`,
      //     query: {
      //         roomId
      //     }
      // })
      this.$emit('on-open-room', this.room)
    }
  }
}
</script>

<style lang="less" scoped>
.sidebar {
    width: 348px;
    border: 1px solid #efeff1;
    border-radius: 4px;
}
.close-btn {
    margin: 0 0 0 10px;
}
.line {
    border-bottom: 1px dashed #ddd;
    padding: 0 0 10px;
    margin: 0 20px 10px;
    .info-right {
        padding-left: 0;
    }
}
.line-top {
    border-top: 1px dashed #ddd;
    padding: 15px 0 0;
    margin: 10px 0 0;
}
.info-right {
    text-align: left;
    line-height: 3;
    padding-left: 20px;
}
.red {
    color: #f3565d;
}
.green {
    color: #05bac5;
}

.add-pwd-room-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 0 10px 10px;
}
.add-pwd-line {
    border-bottom: 1px solid #ddd;
    margin: 0 0 10px;
    padding: 0 0 5px;
}
.add-pwd-label {
    text-align: right;
}
.add-pwd-cell {
    padding: 0 0 5px;
}
.add-pwd-form-item {
    margin-bottom: 5px;
}
.float-right {
    float: right;
    margin-right: 14px;
    margin-top: 3px;
    width: 50px;
    height: 30px;
}
.add-device-btn {
    width: 120px;
    height: 38px;
    font-size: 15px;
}
.special-line {
    padding: 35px 0;
}
.ellipsis {
      width: 220px;
      height: 50px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
</style>